<template>
  <div class="container">
    <div class="app-container">
      <el-row class="row-container">
        <!-- 添加权限 -->
        <el-button type="primary" size="small" style="margin-top: 20px" @click="addPermission(0,1)">添加权限</el-button>
        <!-- 组织架构表单 -->
        <el-table border :data="list" row-key="id" style="margin-left: 50px; margin-top: 20px;">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type === 1" type="text" size="mini" @click="addPermission(row.id,2)">添加</el-button>
              <el-button type="text" size="mini" @click="editPermission(row.id)">编辑</el-button>
              <el-button type="text" size="mini" @click="delPermission(row.id)">删除</el-button>
              <el-button type="text" size="mini" @click="assignPermissions(row.id)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </div>

    <!-- 权限分配弹层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="assignDialogVisible"
      width="40%"
      @close="resetAssignForm"
    >
      <el-row v-loading="assignLoading">
        <el-col :span="24" style="margin-bottom: 10px;">
          <el-button type="text" @click="checkAll">全选</el-button>
          <el-button type="text" @click="uncheckAll">全不选</el-button>
        </el-col>
        <el-col :span="24">
          <el-tree
            ref="permissionTree"
            :data="list"
            show-checkbox
            node-key="id"
            :default-checked-keys="defaultCheckedKeys"
            :props="{
              label: 'name',
              children: 'children'
            }"
            class="permission-tree"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePermissions">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 原有弹层 -->
    <el-dialog
      :title="`${showText}权限点`"
      :visible.sync="DialogVisible"
      width="30%"
      @close="btnCancel"
    >
      <el-form ref="PerForm" :model="PermissionForm" :rules="PermissionRules" label-width="120px">
        <el-form-item label="权限名称" prop="name" style="width: 90%;">
          <el-input v-model="PermissionForm.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code" style="width: 90%;">
          <el-input v-model="PermissionForm.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description" style="width: 90%;">
          <el-input v-model="PermissionForm.description" />
        </el-form-item>
        <el-form-item label="开启">
          <el-switch
            v-model="PermissionForm.enVisible"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <el-row slot="footer" justify="center" type="flex">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPermissionAPI,
  delPermissionAPI,
  getPermissionListAPI,
  updataPermissionAPI,
  getPermissionDetailAPI
} from '@/api/permission'
import { getRoleDetailAPI } from '@/api/role'
import { transListToTreeDate } from '@/utils'

export default {
  name: 'Permission',
  data() {
    return {
      list: [],
      DialogVisible: false,
      assignDialogVisible: false,
      assignLoading: false,
      PermissionForm: {
        name: '',
        code: '',
        description: '',
        type: '',
        pid: '',
        enVisible: '0'
      },
      PermissionRules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
      },
      currentRoleId: null,
      rolePermissions: [],
      defaultCheckedKeys: []
    }
  },
  computed: {
    showText() {
      return this.PermissionForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      this.list = transListToTreeDate(await getPermissionListAPI(), 0)
    },

    // 分配权限
    async assignPermissions(roleId) {
      this.assignLoading = true
      try {
        console.log('Fetching role details for roleId:', roleId)
        this.currentRoleId = roleId
        const roleDetail = await getRoleDetailAPI(roleId)
        console.log('Role details:', roleDetail)

        if (!roleDetail || !roleDetail.permissions) {
          throw new Error('Invalid role details response')
        }

        this.defaultCheckedKeys = roleDetail.permissions
        this.assignDialogVisible = true
      } catch (error) {
        console.error('Error fetching role permissions:', error)
        this.$message.error('获取角色权限失败: ' + error.message)
      } finally {
        this.assignLoading = false
      }
    },

    // 全选
    checkAll() {
      this.$refs.permissionTree.setCheckedKeys(this.list.map(node => node.id))
    },

    // 全不选
    uncheckAll() {
      this.$refs.permissionTree.setCheckedKeys([])
    },

    // 重置分配表单
    resetAssignForm() {
      this.currentRoleId = null
      this.defaultCheckedKeys = []
      this.$refs.permissionTree.setCheckedKeys([])
    },

    // 保存权限分配
    async savePermissions() {
      const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
      try {
        await this.$api.role.updateRolePermissions({
          id: this.currentRoleId,
          permissions: checkedKeys
        })
        this.$message.success('权限分配成功')
        this.assignDialogVisible = false
        this.$emit('permission-assigned')
      } catch (error) {
        console.error('Error saving permissions:', error)
        this.$message.error('权限分配失败: ' + error.message)
      }
    },

    // 原有方法保持不变
    btnOk() {
      this.$refs.PerForm.validate().then(() => {
        if (this.PermissionForm.id) {
          return updataPermissionAPI(this.PermissionForm)
        }
        return addPermissionAPI(this.PermissionForm)
      }).then(() => {
        this.$message.success('新增成功')
        this.getPermissionList()
        this.DialogVisible = false
      })
    },
    btnCancel() {
      this.PermissionForm = {
        name: '',
        code: '',
        description: '',
        type: '',
        pid: '',
        enVisible: '0'
      }
      this.DialogVisible = false
      this.$refs.PerForm.resetFields()
    },
    addPermission(pid, type) {
      this.PermissionForm.pid = pid
      this.PermissionForm.type = type
      this.DialogVisible = true
    },
    async editPermission(id) {
      this.PermissionForm = await getPermissionDetailAPI(id)
      this.DialogVisible = true
    },
    async delPermission(id) {
      try {
        await this.$confirm('确定要删除该数据吗')
        await delPermissionAPI(id)
        this.getPermissionList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped>
.row-container {
  padding: 30px;
  margin: 10px 20px;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
}
</style>
